package com.itany.ums.servlet;

import com.itany.ums.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

/**
 * @author shixiaojun@itany
 */
@WebServlet("*.user")
public class UserServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求字符集
        request.setCharacterEncoding("utf-8");
        // 设置响应格式
        response.setContentType("text/html;charset=utf-8");
        // 获取当前访问的请求
        String path = request.getServletPath();
        switch (path){
            case "/register.user":
                register(request,response);
                break;
            case "/login.user":
                login(request,response);
                break;
            case "/logout.user":
                logout(request,response);
                break;
            default:
                PrintWriter out = response.getWriter();
                out.println("<h1 style='color:red;'>对不起,您访问的资源不存在</h1>");
        }
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 清空session中的数据
        request.getSession().invalidate();
        // 重新跳转到主页
        response.sendRedirect(request.getContextPath()+"/pages/main.jsp");
    }
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户输入的用户名与密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 通过JDBC访问数据库,判断该用户名与密码是否正确
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/ums?useUnicode=true&characterEncoding=utf-8";
        User user = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","root");
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where username = ? ")
                    .append(" and password = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            // 获取结果集
            rs = ps.executeQuery();
            if(rs.next()){
                // 如果查询到数据了,则表示用户名与密码正确
                // 可以将查询到的数据映射成Java对象
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                // 将查询到的用户信息保存到会话session中
                request.getSession().setAttribute("user",user);
                // 重定向到主页
                response.sendRedirect(request.getContextPath()+"/pages/main.jsp");
                // 流程结束
                return;
            }
            // 如果没有查询到数据,则说明用户名或者密码错误了
            request.setAttribute("loginMsg","用户名或密码错误");
            // 转发到登录页面重新登录
            request.getRequestDispatcher("/pages/login.jsp").forward(request,response);
        } catch (ClassNotFoundException e) {
            request.setAttribute("loginMsg","未注册驱动");
            request.getRequestDispatcher("/pages/login.jsp").forward(request,response);
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("loginMsg","数据访问异常");
            // 转发到登录页面重新登录
            request.getRequestDispatcher("/pages/login.jsp").forward(request,response);
        }

    }
    public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取前台传递过来的表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");

        // 通过JDBC实现用户注册的功能
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/ums?useUnicode=true&characterEncoding=utf-8";
        try {
            // 1.注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2.获取连接
            conn = DriverManager.getConnection(url,"root","root");

            // 判断该用户名是否已经被注册
            // 即:根据用户名查询用户信息
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where username = ? ")
                    .toString();
            // 3.获取状态集
            ps = conn.prepareStatement(sql);
            // 设置状态集参数,有几个占位符就设置几个参数
            ps.setString(1,username);
            // 4.获取结果集
            rs = ps.executeQuery();
            // 判断结果集中是否存在数据
            if(rs.next()){
                // 如果存在结果,则说明数据库中已经存在
                // 即:该用户已经被注册过了
                // 将错误消息存储到request作用域
                request.setAttribute("registerMsg","该用户已经被注册");
                // 转发到注册页面
                request.getRequestDispatcher("/pages/register.jsp").forward(request,response);
                // 此时不需要进行注册,流程结束
                return;
            }
            // 如果结果集中没有查询到数据,则说明该用户名尚未被注册,可以使用
            // 执行注册的流程
            sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append("   (username,password,phone,address)")
                    .append(" values ")
                    .append("   (?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            // 设置参数
            ps.setString(1,username);
            ps.setString(2,password);
            ps.setString(3,phone);
            ps.setString(4,address);
            // 执行DML操作
            ps.executeUpdate();
            // 成功之后重定向到登录页面
            response.sendRedirect(request.getContextPath()+"/pages/login.jsp");
        } catch (ClassNotFoundException e) {
            request.setAttribute("registerMsg","未注册驱动");
            request.getRequestDispatcher("/pages/register.jsp").forward(request,response);
        } catch (SQLException e) {
            request.setAttribute("registerMsg","数据访问异常");
            request.getRequestDispatcher("/pages/register.jsp").forward(request,response);
        }
    }

}
